<!--  -->
<template>
  <div id="MapView">
    <div id="sketchWidget">
      <div
        id="area-button"
        class="esri-widget esri-widget--button esri-interactive"
        title="绘制区域"
      >
        <span class="esri-icon-polygon"></span>
      </div>
    </div>
  </div>
  <!-- <div id="searchWidget"> -->
  <!-- <p class="labelOfSearchWidget">经度：</p>
            <input type="text" class="inputOfSearchWidget" id="xLal">
            <p class="labelOfSearchWidget">纬度：</p>
            <input type="text" class="inputOfSearchWidget" id="yLal">
            <div id="btnLal">查询</div> -->
  <!-- <el-input v-model="inputX" class="inputOfSearchWidget" id="xLal" placeholder="经度"></el-input> -->
  <!-- <el-input v-model="inputY" class="inputOfSearchWidget" id="yLal" placeholder="纬度"></el-input> -->
  <!-- <el-button id="btnLal" @click="searchClick">查询</el-button> -->
  <!-- </div> -->
</template>

<script>
import { loadModules } from 'esri-loader'
// import consts from '@/consts'
import { fakeRobotData } from '../fakeRobot'

export default {
  data() {
    return {}
  },

  components: {},

  computed: {},
  mounted() {
    this.createView()
  },

  methods: {
    //创建视图
    createView() {
      const options = {
        // url: 'http://szls.chiefdata.net/bdi-dt/arcgis/init.js',
        url: 'https://js.arcgis.com/4.20/',
        // css: 'http://szls.chiefdata.net/bdi-dt/arcgis/esri/themes/light/main.css',
        css: 'https://js.arcgis.com/4.20/esri/themes/light/main.css',
      }

      loadModules(
        [
          'esri/Map',
          'esri/views/MapView',
          'esri/geometry/Extent',
          'esri/layers/ImageryLayer',
          'esri/geometry/SpatialReference',
          'esri/layers/GraphicsLayer',
          'esri/symbols/SimpleMarkerSymbol',
          'esri/symbols/SimpleLineSymbol',
          'esri/Color',
          'esri/geometry/Point',
          'esri/Graphic',
          'esri/symbols/TextSymbol',
          'esri/symbols/Font',
          'dojo/on',
          'dojo/dom',
          'dojo/dom-attr',
          'esri/widgets/Search',
          'esri/widgets/Editor',
          'esri/layers/FeatureLayer',
          'esri/symbols/PictureMarkerSymbol',
          'esri/PopupTemplate',
          'esri/widgets/Zoom',
          'esri/widgets/Widget',
          'esri/widgets/Sketch/SketchViewModel',
          'esri/geometry/Polygon',
          'esri/views/2d/draw/Draw',
          'dojo/domReady!',
        ],
        options
      ).then(
        ([
          Map,
          MapView,
          Extent,
          ImageryLayer,
          SpatialReference,
          GraphicsLayer,
          SimpleMarkerSymbol,
          SimpleLineSymbol,
          Color,
          Point,
          Graphic,
          TextSymbol,
          Font,
          On,
          Dom,
          DomAttr,
          Search,
          Editor,
          FeatureLayer,
          PictureMarkerSymbol,
          PopupTemplate,
          Zoom,
          Widget,
          SketchViewModel,
          Polygon,
          Draw,
        ]) => {
          // const initTiledExtent = new Extent({
          //   xmin: 113.589735,
          //   ymin: 22.365199,
          //   xmax: 113.59647,
          //   ymax: 22.369111,
          //   spatialReference: { wkid: 4326 },
          // })

          const map = new Map({
            basemap: 'streets',
            logo: false,
          })

          const tiledMapServiceLayerUrl =
            'http://192.168.68.115/arcgis/rest/services/JoanieTest/GangWanImg0922/ImageServer'
          // const tiledMapServiceLayerUrl =
          // 'http://192.168.68.141/arcgis/rest/services/JoanieTest/JoanieTest_DBO_GangWanOnePark/ImageServer'
          // const tiledMapServiceLayerUrl =
          //   'http://localhost:6080/arcgis/rest/services/GangWan/ImageServer'

          const tiledMapServiceLayer = new ImageryLayer({
            url: tiledMapServiceLayerUrl,
          })
          map.add(tiledMapServiceLayer)

          const view = new MapView({
            container: 'MapView', // Reference to the DOM node that will contain the view
            map: map, // References the map object created in step 3
            SpatialReference: { wkid: 4326 },
            constraints: {
              rotationEnabled: false,
            },
            ui: {
              components: ['attribution'],
            },
          })

          // 放外面，放在const view = new MapView({})里面不好使
          view.zoom = 17
          view.center = [113.596484, 22.367019]
          // view.extent = initTiledExtent

          view.on('key-down', event => {
            const prohibitedKeys = ['+', '-', 'Shift', '_', '=']
            const keyPressed = event.key
            if (prohibitedKeys.indexOf(keyPressed) !== -1) {
              event.stopPropagation()
            }
          })

          view.on('mouse-wheel', event => {
            event.stopPropagation()
          })

          view.on('double-click', event => {
            event.stopPropagation()
          })

          view.on('drag', event => {
            event.stopPropagation()
          })

          /*****************************************************************
           * add a search widget
           * **************************************************************/
          // add a graphic layer for showing the location
          const searchWidget = new Search({
            view: view,
          })

          view.ui.add(searchWidget, {
            position: 'top-left',
            index: 2,
          })

          /*****************************************************************
           * add a sketch widget
           * **************************************************************/
          // const graphicsLayer = new GraphicsLayer();

          // const sketchWidget = new Sketch({
          //   layer: graphicsLayer,
          //   view: view,
          //   // graphic will be selected as soon as it is created
          //   creationMode: 'update'
          // })

          // view.ui.add(sketchWidget, {
          //   position:'top-right'
          // });

          const areaLayer = new GraphicsLayer()

          view.ui.add('area-button', 'top-right')

          view.when(function () {
            var draw = new Draw({
              view: view,
            })
            var drawAreaButton = document.getElementById('area-button')
            drawAreaButton.onclick = function () {
              // view.graphics.removeAll();//清除之前的绘制
              areaLayer.removeAll()
              enableCreateArea(draw, view)
              // enableCompletePolygon(draw, view);
            }
          })

          function enableCreateArea(draw, view) {
            var action = draw.create('polygon', {
              mode: 'hybrid', //点击方式加点 freehand hybrid click
            })

            view.focus() //获取焦点

            action.on('vertex-add', createPolygon) // 顶点添加事件
            action.on('vertex-remove', createPolygon) //顶点移除事件
            action.on('cursor-update', createPolygon) // 鼠标移动事件
            // action.on('draw-complete', completePolygon);// 绘制完成事件
          }

          function createPolygon(event) {
            var vertices = event.vertices //获取所有顶点
            // view.graphics.removeAll();//清除之前绘制
            areaLayer.removeAll()

            // 生成绘制的图形
            var areaGraphic = new Graphic({
              geometry: new Polygon({
                hasZ: false,
                hasM: false,
                rings: [vertices],
                spatialReference: view.spatialReference,
              }),
              symbol: {
                type: 'simple-fill', // autocasts as new SimpleFillSymbol()
                color: [51, 51, 204, 0.9],
                style: 'solid',
                outline: {
                  // autocasts as new SimpleLineSymbol()
                  color: 'red',
                  width: 1,
                },
              },
            })
            // 将绘制的图形添加到view
            areaLayer.add(areaGraphic)
          }

          // function enableCompletePolygon(draw,view){
          //   var action = draw.create('polygon', {
          //       mode: 'double-click'//点击方式加点
          //   });
          //   view.focus();
          //   action.on('cursor-update', createPolygon);
          //   action.on('draw-complete', completePolygon);
          // }

          // function completePolygon(event){
          //   console.info('double-click')
          //   var vertices = event.vertices;//获取所有顶点
          //   // view.graphics.removeAll();//清除之前绘制
          //   // areaLayer.removeAll()
          //   var areaGraphic = new Graphic({
          //       geometry: new Polygon({
          //           hasZ: false,
          //           hasM: false,
          //           rings: [vertices],
          //           spatialReference: view.spatialReference
          //       }),
          //       symbol: {
          //           type: 'simple-fill', // autocasts as new SimpleFillSymbol()
          //           color: [51,51, 204, 0.9],
          //           style: 'solid',
          //           outline: { // autocasts as new SimpleLineSymbol()
          //               color: 'red',
          //               width: 1
          //           }
          //       }
          //   });
          //   areaLayer.add(areaGraphic);
          // }
          map.add(areaLayer)

          /*****************************************************************
           * show lal info
           * **************************************************************/
          // add a graphic layer about showing the moving lal
          var getLalGraphicLayer = new GraphicsLayer()
          map.add(getLalGraphicLayer)

          // set a marker symbol
          var lalSymbol = new SimpleMarkerSymbol(
            SimpleMarkerSymbol.STYLE_DIAMOND,
            20,
            new SimpleLineSymbol(SimpleLineSymbol.STYLE_DIAMOND, new Color([0, 0, 0]), 1),
            new Color([255, 255, 255, 1])
          )

          // show the point of longitude and latitude
          view.on('pointer-move', function (evt) {
            // get longitude and latitude
            const { longitude, latitude } = view.toMap({ x: evt.x, y: evt.y })
            const lon = longitude.toFixed(6)
            const lat = latitude.toFixed(6)
            // const lon = longitude
            // const lat = latitude
            const lalPoint = new Point(lon, lat)

            // add a marker symbol
            getLalGraphicLayer.removeAll()
            const lalPointGraphic = new Graphic(lalPoint, lalSymbol)
            getLalGraphicLayer.add(lalPointGraphic)

            // set a text symbol
            const lalTextSymbol = new TextSymbol('(' + lon + ',' + lat + ')')
            lalTextSymbol.color = [255, 255, 255]
            lalTextSymbol.font = {
              size: '14pt',
            }
            lalTextSymbol.xOffset = 0
            lalTextSymbol.yOffset = '14px'

            // add a text symbol
            const lalTextGraphic = new Graphic(lalPoint, lalTextSymbol)
            getLalGraphicLayer.add(lalTextGraphic)
          })

          /*****************************************************************
           * create a point graphic
           * **************************************************************/
          const point = {
            type: 'point',
            longitude: 113.5934,
            latitude: 22.3673,
          }

          const markerSymbol = {
            type: 'simple-marker',
            color: [226, 119, 40],
            outline: {
              color: [255, 255, 255],
              width: 2,
            },
          }

          const pointAtt = {
            Name: '测试点',
            Id: 'pi-000001',
            经纬度: point.longitude + ',' + point.latitude,
          }

          const pointGraphic = new Graphic({
            geometry: point,
            symbol: markerSymbol,
            attributes: pointAtt,
            popupTemplate: {
              title: '{Name}',
              content: [
                {
                  type: 'fields',
                  fieldInfos: [
                    {
                      fieldName: 'Name',
                    },
                    {
                      fieldName: 'Id',
                    },
                    {
                      fieldName: '经纬度',
                    },
                  ],
                },
                {
                  type: 'media',
                  mediaInfos: [
                    // {
                    //   title: '<b>Count by type</b>',
                    //   type: 'pie-chart', // Autocasts as new PieChartMediaInfo()
                    //   caption: '',
                    //   // Autocasts as new ChartMediaInfoValue()
                    //   value: {
                    //     fields: ['relationships/0/Point_Count_COMMON'],
                    //     normalizeField: null,
                    //     tooltipField: 'relationships/0/COMMON'
                    //   }
                    // },
                    {
                      // title: '<b>Mexican Fan Palm</b>',
                      type: 'image',
                      // caption: 'tree species',
                      value: {
                        sourceURL:
                          'https://www.sunset.com/wp-content/uploads/96006df453533f4c982212b8cc7882f5-800x0-c-default.jpg',
                      },
                    },
                  ],
                },
              ],
            },
          })

          /****************************
           * Create a polyline graphic
           ****************************/
          const polyline = {
            type: 'polyline',
            paths: [
              [113.592388, 22.368088],
              [113.591949, 22.366343],
              [113.590612, 22.366013],
            ],
          }

          const lineSymbol = {
            type: 'simple-line',
            color: [226, 119, 40],
            width: 4,
          }

          const lineAtt = {
            Name: '测试线1',
            Id: 'pl-000001',
          }

          const polylineGraphic = new Graphic({
            geometry: polyline,
            symbol: lineSymbol,
            attributes: lineAtt,
            popupTemplate: {
              title: '{Name}',
              content: [
                {
                  type: 'fields',
                  fieldInfos: [
                    {
                      fieldName: 'Name',
                    },
                    {
                      fieldName: 'Id',
                    },
                  ],
                },
              ],
            },
          })

          /***************************
           * Create a polygon graphic
           ***************************/
          // Create a polygon geometry
          const polygon = {
            type: 'polygon',
            rings: [
              [113.593899, 22.368824],
              [113.593937, 22.367063],
              [113.595436, 22.366085],
              [113.595598, 22.367805],
            ],
          }

          const fillSymbol = {
            type: 'simple-fill',
            color: [227, 139, 79, 0.8],
            outline: {
              color: [255, 255, 255],
              width: 1,
            },
          }

          const polygonAtt = {
            Name: '测试区域1',
            Id: 'pg-000001',
          }

          const polygonGraphic = new Graphic({
            geometry: polygon,
            symbol: fillSymbol,
            attributes: polygonAtt,
            popupTemplate: {
              title: '{Name}',
              content: [
                {
                  type: 'fields',
                  fieldInfos: [
                    {
                      fieldName: 'Name',
                    },
                    {
                      fieldName: 'Id',
                    },
                  ],
                },
              ],
            },
          })

          var centerPoint = polygonGraphic //.centeroid
          console.info(centerPoint, 'centerPoint')

          /*****************************************************************
           * create a point graphic(picture)
           * **************************************************************/
          const arrow = {
            type: 'point',
            longitude: 113.59212,
            latitude: 22.365948,
          }

          const pictureSymbol = {
            type: 'picture-marker',
            url: 'https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png',
            width: '40px',
            height: '40px',
          }

          const pictureAtt = {
            Name: '测试区域1',
            Id: 'pg-000001',
          }

          const pictureGraphic = new Graphic({
            geometry: arrow,
            symbol: pictureSymbol,
            attributes: pictureAtt,
            popupTemplate: {
              title: '{Name}',
              content: [
                {
                  type: 'fields',
                  fieldInfos: [
                    {
                      fieldName: 'Name',
                    },
                    {
                      fieldName: 'Id',
                    },
                  ],
                },
              ],
            },
          })

          // console.log('err')

          setInterval(function () {
            // view.graphics.remove(pictureGraphic)
            if (view.graphics.items[3].visible === true) {
              view.graphics.items[3].visible = false
            } else {
              view.graphics.items[3].visible = true
            }
          }, 1000)
          // console.log(view.graphics)

          view.graphics.addMany([pointGraphic, polylineGraphic, polygonGraphic, pictureGraphic])

          /*****************************************************************
           * create a route
           * **************************************************************/
          var routeGraphicsLayer = new GraphicsLayer()

          for (var temp in fakeRobotData) {
            const routePoint = {
              type: 'point',
              longitude: fakeRobotData[temp].longitude,
              latitude: fakeRobotData[temp].latitude,
            }

            const routePointSymbol = {
              type: 'simple-marker',
              color: [226, 119, 40],
              outline: {
                color: [255, 255, 255],
                width: 2,
              },
            }

            const routePointAtt = {
              Name: '测试点',
              Id: 'pi-000001',
              经纬度: point.longitude + ',' + point.latitude,
            }

            const routePointGraphic = new Graphic({
              geometry: routePoint,
              symbol: routePointSymbol,
              attributes: routePointAtt,
              popupTemplate: {
                title: '{Name}',
                content: [
                  {
                    type: 'fields',
                    fieldInfos: [
                      {
                        fieldName: 'Name',
                      },
                      {
                        fieldName: 'Id',
                      },
                    ],
                  },
                ],
              },
            })

            routeGraphicsLayer.add(routePointGraphic)

            // view.graphics.add(routePointGraphic)
          }
          map.add(routeGraphicsLayer)

          // console.info(map, 'map')
          // var i, j
          // for (i in map.allLayers.items) {
          //   console.info(map.allLayers.items[i].type, i + ',type')
          //   if (map.allLayers.items[i].graphics) {
          //     for (j in map.allLayers.items[i].graphics.items) {
          //       console.info(
          //         map.allLayers.items[i].graphics.items[j].geometry.type,
          //         i + ',' + j + ',geometry.type'
          //       )
          // console.info(map,'map')
          /*****************************************************************
           * create a robot
           * **************************************************************/
          var robotGraphicsLayer = new GraphicsLayer()
          var robot_i = 0

          setInterval(function () {
            robotGraphicsLayer.removeAll()

            robot_i++
            while (robot_i === fakeRobotData.length) {
              robot_i = 0
            }

            const robotPoint = {
              type: 'point',
              longitude: fakeRobotData[robot_i].longitude,
              latitude: fakeRobotData[robot_i].latitude,
            }

            const robotAtt = {
              Name: '测试机器人01',
              Id: 'rb-000001',
            }

            const robotGraphic = new Graphic({
              geometry: robotPoint,
              symbol: pictureSymbol,
              attributes: robotAtt,
              popupTemplate: {
                title: '{Name}',
                content: [
                  {
                    type: 'fields',
                    fieldInfos: [
                      {
                        fieldName: 'Name',
                      },
                      {
                        fieldName: 'Id',
                      },
                    ],
                  },
                ],
              },
            })
            robotGraphicsLayer.add(robotGraphic)
          }, 1000)

          map.add(robotGraphicsLayer)

          // --------
          var i, j
          for (i in map.allLayers.items) {
            console.info(map.allLayers.items[i].type, i + ',type')
            if (map.allLayers.items[i].graphics) {
              for (j in map.allLayers.items[i].graphics.items) {
                console.info(
                  map.allLayers.items[i].graphics.items[j].geometry.type,
                  i + ',' + j + ',geometry.type'
                )
              }
            }
          }

          console.info(view, 'view')
          for (var k in view.graphics.items) {
            console.info(view.graphics.items[k].geometry.type, k + ',view')
          }
        }
      )
    },
  },
}
</script>
<style lang='scss' scoped>
#MapView {
  width: 100%;
  height: 100%;
}

#searchWidget {
  position: absolute;
  top: 30px;
  left: 70px;
  z-index: 1;
  width: 380px;
  height: 30px;
  background: #fff;
  border: 1px solid #fff;
  border-radius: 5px;
}

.labelOfSearchWidget {
  display: inline;
  float: left;
  width: 50px;
  height: 100%;
  margin-top: 3px;
  margin-left: 2px;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
}

.inputOfSearchWidget {
  float: left;
  width: 100px;
  height: 20px;
  margin-top: 3px;
}

#btnLal {
  display: inline-block;
  width: 60px;
  height: 22px;
  // margin-top: 2px;//
  padding: 0;
  margin-left: 12px;
  font-size: 14px;
  font-weight: bold;
  line-height: 30px;
  color: #000;
  text-align: center; //
}
</style>
